using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;

public class LoginUI : MonoBehaviour
{
    [Header("UI组件")]
    public TMP_InputField usernameInput;    // 用户名输入框
    public TMP_InputField passwordInput;    // 密码输入框
    public Button loginButton;              // 登录按钮
    public Button registerButton;           // 注册按钮
    public TextMeshProUGUI messageText;     // 提示信息文本
    public GameObject loadingPanel;         // 加载面板

    [Header("场景设置")]
    public string gameSceneName = "BeginningScene";  // 游戏主场景名称

    private void Start()
    {
        // 初始化按钮监听
        loginButton.onClick.AddListener(OnLoginButtonClick);
        registerButton.onClick.AddListener(OnRegisterButtonClick);

        // 初始化密码输入框为密码模式
        passwordInput.contentType = TMP_InputField.ContentType.Password;

        // 隐藏加载面板
        if (loadingPanel != null)
            loadingPanel.SetActive(false);
    }

    private void OnLoginButtonClick()
    {
        // 获取输入的用户名和密码
        string username = usernameInput.text;
        string password = passwordInput.text;

        // 验证输入
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        {
            ShowMessage("用户名和密码不能为空！");
            return;
        }

        // 显示加载面板
        if (loadingPanel != null)
            loadingPanel.SetActive(true);

        // 这里添加你的登录验证逻辑
        StartCoroutine(LoginProcess(username, password));
    }

    private IEnumerator LoginProcess(string username, string password)
    {
        // 模拟网络请求延迟
        yield return new WaitForSeconds(1f);

        // 这里替换为实际的登录验证逻辑
        bool loginSuccess = ValidateLogin(username, password);

        if (loginSuccess)
        {
            ShowMessage("登录成功！");
            // 加载游戏场景
            UnityEngine.SceneManagement.SceneManager.LoadScene(gameSceneName);
        }
        else
        {
            ShowMessage("用户名或密码错误！");
        }

        // 隐藏加载面板
        if (loadingPanel != null)
            loadingPanel.SetActive(false);
    }

    private bool ValidateLogin(string username, string password)
    {
        // 这里添加实际的登录验证逻辑
        // 示例：简单的用户名密码验证
        return username == "123456" && password == "123456";
    }

    private void OnRegisterButtonClick()
    {
        // 这里添加注册按钮点击逻辑
        ShowMessage("注册功能开发中...");
    }

    private void ShowMessage(string message)
    {
        if (messageText != null)
        {
            messageText.text = message;
            // 3秒后清除消息
            StartCoroutine(ClearMessage());
        }
    }

    private IEnumerator ClearMessage()
    {
        yield return new WaitForSeconds(3f);
        messageText.text = "";
    }

    private void OnDestroy()
    {
        // 移除按钮监听
        loginButton.onClick.RemoveListener(OnLoginButtonClick);
        registerButton.onClick.RemoveListener(OnRegisterButtonClick);
    }
} 